package com.sitanyun.merchant.guide.frament.view.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.ImageLoadBean;
import com.sitanyun.merchant.guide.bean.WxImagesBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.frament.presenter.impl.WxImageAPresenterImpl;
import com.sitanyun.merchant.guide.frament.presenter.inter.IWxImageAPresenter;
import com.sitanyun.merchant.guide.frament.view.inter.IWxImageAView;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.weiht.GlideEngine;
import com.sitanyun.merchant.guide.weiht.ImageLoadUtrils;
import com.sitanyun.merchant.guide.weiht.Loading_view;
import com.sitanyun.merchant.guide.weiht.PictureUtils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 二维码
 */
public class WxImageActivity extends BaseActivity implements IWxImageAView {

    @BindView(R.id.image_load)
    ImageView imageLoad;
    @BindView(R.id.img_delete)
    TextView imgDelete;
    @BindView(R.id.img_min)
    TextView imgMin;
    private String TAKE_PHOTO_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    public static final int RC_CHOOSE_PHOTO = 2;
    private String filePath;
    private IWxImageAPresenter mIWxImageAPresenter;

    private String wximg;
  private int type=1;
    private ImageLoadBean.DataBean imagelist =new ImageLoadBean.DataBean();
    private Loading_view loading_view;
    private String fileId="";

    @Override
    public int getLayoutId() {
        return R.layout.activity_wx_image;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setFindViewById(true);
        setTitleStr("我的二维码");
    }

    @Override
    public void initView() {
        wximg = getIntent().getStringExtra("wximg");
       // wxid = getIntent().getStringExtra("wxid");
        if (wximg.equals("null")){
            type=1;
            Glide.with(WxImageActivity.this).load(R.mipmap.img_wx).into(imageLoad);
        }else {
            type=2;
            Glide.with(WxImageActivity.this).load(wximg).into(imageLoad);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIWxImageAPresenter = new WxImageAPresenterImpl(this);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        loading_view = new Loading_view(WxImageActivity.this, R.style.CustomDialog);
    }

    @OnClick({R.id.image_load, R.id.img_delete, R.id.img_min})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_load:
                type=2;
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //未授权，申请授权(从相册选择图片需要读取存储卡的权限)
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, RC_CHOOSE_PHOTO);
                } else {
                    //已授权，获取照片
                  //    choosePhoto();
                    PictureSelector.create(WxImageActivity.this)
                            .openGallery(PictureMimeType.ofImage())
                            .selectionMode(PictureConfig.SINGLE)
                            .loadImageEngine(GlideEngine.createGlideEngine())
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                }

                break;
            case R.id.img_delete:
                type=1;
               Glide.with(WxImageActivity.this).load(R.mipmap.img_wx).into(imageLoad);
                fileId = imagelist.getFileId();
                fileId="";
                break;
            case R.id.img_min:
                ///删除和图片验证
                if (wximg.equals("null")){
                    if (imagelist.getFileId()==null){

                        ToastUtil.showToast(WxImageActivity.this,"请上传二维码");
                        return;
                    }else {
                           //保存
                        mIWxImageAPresenter.getqrcodeld(imagelist.getFileId());
                    }

                }else {
                    if (imagelist.getFileId()==null){
                     if (type==1){
                         ToastUtil.showToast(WxImageActivity.this,"请上传二维码");
                         return;
                     }else {
                         finish();
                     }

                    }else {
                          //保存
                        mIWxImageAPresenter.getqrcodeld(imagelist.getFileId());
                    }
                }

                break;
        }
    }
//   //获取系统相册图片
//    private void choosePhoto() {
//        Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
//        intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        startActivityForResult(intentToPickPic, RC_CHOOSE_PHOTO);
//    }

    /**
     * 图片地址回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList1 = PictureSelector.obtainMultipleResult(data);
                    Log.i("TAG", "onActivityResult: 图片地址 ： " + new Gson().toJson(selectList1));
                    if (selectList1 != null && selectList1.size() != 0) {
                        //图片压缩
                        PictureUtils pictureUtils = new PictureUtils();
                        Bitmap bitmap = pictureUtils.getimage(selectList1.get(0).getRealPath());
                        //获取文件类型
                        int i = selectList1.get(0).getRealPath().lastIndexOf(".");
                        String s = selectList1.get(0).getRealPath().substring(i, selectList1.get(0).getRealPath().length());
                        String mitls = Calendar.getInstance().getTimeInMillis() + s;
                        String path = TAKE_PHOTO_PATH + "/" + mitls;
                        String mitl = path.substring(path.length() - 17);

                        try {
                            pictureUtils.saveBitmap(bitmap, path, 1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        String img = ImageLoadUtrils.imageToBase64(path);
                       // String img = ImageLoadUtrils.imgToBase64String(path);
                        HashMap<String, String> hashMap = new HashMap<String, String>();
                        hashMap.put("shard", "data:image/jpg;base64," + img);
                        hashMap.put("fileUsage", "BP");
                        hashMap.put("name", mitl);//文件名
                        hashMap.put("suffix", s);//后缀
                        hashMap.put("fileSize",bitmap.getByteCount() + "");//文件大小
                        hashMap.put("shardKey", bitmap.getGenerationId() + "");//分片主键
                        loading_view.show();
                        OkHttpUtils.postString()
                                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                                .addHeader("Content-Type", "application/json")
                                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                                .url(Urls.loadimage)
                                .content(new Gson().toJson(hashMap))
                                .build().execute(new StringCallbacks() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                loading_view.dismiss();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                ImageLoadBean baseEntity = new Gson().fromJson(response, ImageLoadBean.class);
                                if (baseEntity.getCode() == 0) {
                                    type=2;
                                 imagelist =   baseEntity.getData();
                                    filePath = baseEntity.getData().getFilePath();
                                    loading_view.dismiss();
                                    Glide.with(WxImageActivity.this).load(filePath).into(imageLoad);
                                } else {
                                    loading_view.dismiss();
                                  ToastUtil.showToast(WxImageActivity.this, "" + baseEntity.getMsg());
                                }
                            }
                        });


                    }
                    break;

            }
        }
    }

    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IWxImageAView.RESPONSE_ONE) {
            WxImagesBean wxImagesBean = (WxImagesBean) response;
            if (wxImagesBean.getCode() == 0) {
                ToastUtil.showToast(WxImageActivity.this, "上传成功");
                finish();
            } else {
                ToastUtil.showToast(WxImageActivity.this, wxImagesBean.getMsg()+"");
            }
        }
    }
}
